package com.cwz.mq.ack.task;

import com.cwz.mq.ack.constant.MsgLogConstants;
import com.cwz.mq.ack.entity.MsgLog;
import com.cwz.mq.ack.service.MsgLogService;
import com.cwz.mq.ack.utils.MessageHelper;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @program: w-demo
 * @description: mq 消息记录重新投递
 * @author: Wen
 **/
@Component
@EnableScheduling
public class ResendMsg {
	@Autowired
	private MsgLogService msgLogService;
	@Autowired
	private RabbitTemplate rabbitTemplate;

	@Scheduled(cron = "0 * * * * ?")
	public void resend() {
		List<MsgLog> msgLogs = this.msgLogService.selectDeliverFail();
		for (MsgLog msgLog : msgLogs) {
			if (msgLog.getTryCount() >= MsgLogConstants.MAX_TRY_COUNT) {
				if (!msgLog.getStatus().equals(MsgLogConstants.DELIVER_FAIL)) {
					this.msgLogService.updateMsgStatus(msgLog.getMsgId(), MsgLogConstants.DELIVER_FAIL);
				}
				continue;
			}
			this.msgLogService.addMsgTryCount(msgLog.getMsgId(), msgLog.getTryCount());

			this.rabbitTemplate.convertAndSend(msgLog.getExchange(), msgLog.getRoutingKey(),
				MessageHelper.defaultObjToMsg(msgLog.getMsg()), new CorrelationData(msgLog.getMsgId()));
		}
	}
}
